home *** CD-ROM | disk | FTP | other *** search
- /* CPROG6.CPP - some variations on a WHILE loop */
-
- #include <stdio.h>
-
- main()
- {
- int i;
-
-
- printf("CASE 1\n");
-
- i=0; // Set i to zero
- printf("i is now...");
- while( i < 6 ) // If i hasn't reached six yet...
- {
- printf(" %d", i); // Print value of i
- i++; // Increment i
- }
- putchar('\n'); // Putchar prints a single character
- // \n is the newline character
- // which needs to be in quote
- // marks to mark it as a single
- // character. Putchar expects an
- // integer... putchar(33) prints
- // ASCII code 33 (a ! character)
- // '\n', being a recognised
- // code for 'do a carriage return
- // and line feed', is converted
- // to the value 10. Under UNIX
- // 10 is both a CR and a LF. On
- // the PC CR is 13, and LF is 10.
- // '\n' is therefore converted
- // into two characters, but this is
- // a translation into a hardware-
- // specific implementation detail.
- // Conceptually, '\n' is a single
- // character as far as C++ is
- // concerned.
- ////////////////////////////////////////////////////////
- printf("CASE 2\n");
- i=0;
- printf("i is now...");
-
- while( i < 6 )
- printf(" %d", i++); // C++ takes an 'evaluate it then
- // use the resulting number' approach
- // so you can have i incremented
- // in this context. You could also
- // do something like i+=2 which would
- // yield 0+2=2 as the first thing
- // that %d prints. However, i++ is
- // slightly special. It means
- // 'use the value, then increment it'
- // so, first time round the loop, %d
- // is given the value 0 and then i
- // is increased to 1.
-
- putchar('\n');
-
- ////////////////////////////////////////////////////////
-
- printf("CASE 3\n");
- i=0;
- printf("i is now...");
-
- while( i++ < 6 ) // i++ works here but, because of
- printf(" %d", i); // the different position, the
- // first and last values fed to %d
- // are different. i is tested then
- // incremented, so the first time
- // printf() is executed i is
- // already 1. %d will see a value of
- // 6 becuase when i is 5 it is
- // incremented immediately after
- // the test.
- putchar('\n');
-
- ////////////////////////////////////////////////////////
-
- printf("CASE 4\n");
- i= -1;
- printf("i is now...");
-
- while( i < 6 ) // ++i says 'increment the value then
- printf(" %d", ++i); // use it' so, the first one %d
- // sees is -1 + 1 = 0. When i is 5,
- // it goes up to 6 in the printf()
- // line before the loop is aborted
- // by the WHILE test.
-
- putchar('\n');
- }
-